package main

import (
	"fmt"
	_ "gitee.com/chunanyong/dm"
	"gitee.com/moralfly/beego-orm/orm"
	"strings"
)

type Tbl_user_info struct {
	Id            string `orm:"pk" json:"id"`
	PlatformId    string `json:"platform_id"`
	DepartmentId  string `json:"department_id"`
	UserTypeId    string `json:"user_type_id"`
	Name          string `json:"name"`
	Nickname      string `json:"nickname"`
	AccountNumber string `json:"account_number"`
	Password      string `json:"password"`
	Token         string `json:"token"`
	Code          string `json:"code"`
	PhoneNumber   string `json:"phone_number"`
	Image         string `json:"image"`
	CreateTime    string `orm:"auto_now_add;type(datetime)" json:"create_time"`
	UpdateTime    string `orm:"auto_now_add;type(datetime)" json:"update_time"`
	Status        int32  `json:"status"`
}

func (t *Tbl_user_info) Prefix() string {
	return strings.ToUpper(strings.TrimPrefix(t.TableName(), "tbl_"))
}

func (t *Tbl_user_info) TableName() string {
	return "tbl_user_info"
}

func (t *Tbl_user_info) AliasName() string {
	return "用户"
}

func init() {
	const (
		host     = "127.0.0.1"
		port     = 5236
		user     = "SYSDBA"
		password = "123456"
		dbname   = "platform"
	)

	orm.RegisterDriver("dm", orm.DRDm)
	url := fmt.Sprintf("dm://%v:%v@%v:%v?schema=%v", user, password, host, port, dbname)
	orm.RegisterDataBase("default", "dm", url)

	// 需要在init中注册定义的model
	orm.RegisterModel(new(Tbl_user_info))

}

func main() {
	_ = DmDelete()
	_ = DmInsert()
	_ = DmUpdate()
	_ = DmTransaction()
	_ = DmQuery()
}

func DmTransaction() (err error) {
	var transactionHandler = orm.NewOrm()
	if err = transactionHandler.Begin(); err != nil {
		fmt.Println("ERROR: DmTransaction(), 开启事务失败, err=", err)
		return
	}

	defer func() {
		if err != nil {
			_ = transactionHandler.Rollback()
		} else {
			_ = transactionHandler.Commit()
		}
	}()
	var demo = Tbl_user_info{
		Id:         "2",
		Name:       "2",
		CreateTime: "2024-08-05 00:00:00",
		UpdateTime: "2024-08-05 00:00:00",
	}
	_, err = transactionHandler.Insert(&demo)
	if err != nil {
		fmt.Println("Insert", err)
		return err
	}

	return nil
}

func DmQuery() (err error) {
	var num int64
	var demo Tbl_user_info
	err = orm.NewOrm().Raw(`select * from Tbl_user_info where id = '1' `).QueryRow(&demo)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(demo)

	// read one
	u := Tbl_user_info{Id: "2"}
	err = orm.NewOrm().Read(&u)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Read", u)

	var posts []*Tbl_user_info
	num, err = orm.NewOrm().QueryTable(new(Tbl_user_info)).Limit(10).All(&posts)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("All", num, posts)
	for i, i2 := range posts {
		fmt.Println(i, i2)
	}

	var idList []string
	_, err = orm.NewOrm().Raw(`select id from Tbl_user_info `).QueryRows(&idList)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(len(idList), idList)

	var maps []orm.Params
	num, err = orm.NewOrm().Raw("SELECT id FROM Tbl_user_info WHERE name = ?", "astaxie11").Values(&maps)
	if num > 0 {
		fmt.Println(maps[0]["id"])
	}
	fmt.Println("maps", num, maps, err)

	return nil
}

func DmUpdate() (err error) {
	var demo = Tbl_user_info{
		Id:   "1",
		Name: "astaxie11",
	}
	_, err = orm.NewOrm().Update(&demo, []string{"name"}...)
	if err != nil {
		fmt.Println("Update err", err)
	}
	return nil
}

func DmInsert() (err error) {
	var sql = `INSERT INTO tbl_user_info (id, name, nickname, code, create_time, update_time) 
	VALUES ('22', '苏茈茈', '22', '2', '2024-08-05 00:00:00', '2024-08-05 00:00:00')`
	_, err = orm.NewOrm().Raw(sql).Exec()
	if err != nil {
		fmt.Println("Insert Exec", err)
	}

	var demo = Tbl_user_info{
		Id:         "1",
		Name:       "1",
		CreateTime: "2024-08-05 00:00:00",
		UpdateTime: "2024-08-05 00:00:00",
	}
	_, err = orm.NewOrm().Insert(&demo)
	if err != nil {
		fmt.Println("Insert", err)
	}

	var demoMulti = []Tbl_user_info{{
		Id:         "1111",
		Name:       "1111",
		CreateTime: "2024-08-05 00:00:00",
		UpdateTime: "2024-08-05 00:00:00",
	}, {
		Id:         "1122",
		Name:       "1122",
		CreateTime: "2024-08-05 00:00:00",
		UpdateTime: "2024-08-05 00:00:00",
	}}

	_, err = orm.NewOrm().InsertMulti(len(demoMulti), &demoMulti)
	if err != nil {
		fmt.Println("InsertMulti", err)
	}
	return nil
}

func DmDelete() (err error) {
	var num int64
	// delete
	num, err = orm.NewOrm().Delete(&Tbl_user_info{Id: "1"})
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Delete", num)

	_, err = orm.NewOrm().Raw(`DELETE FROM Tbl_user_info WHERE id like '%1%'`).Exec()
	if err != nil {
		fmt.Println("DELETE Exec 1", err)
	}
	return nil
}
